Perform some action on each element of an array but in small portions using JavaScript